<template>
  <div id="map">
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content" class="popup-content"></div>
    </div>
  </div>
</template>
<script>
// import "ol/ol.css";
// import { Map, View, Feature } from "ol";
// // import Vector from "ol/layer/Vector";
// import LayerGroup from "ol/layer/Group";
// import TileLayer from "ol/layer/Tile";
// import TileWMS from "ol/source/TileWMS";
// import VectorSource from "ol/source/Vector";
// import vectorLayer from "ol/layer/Vector";
// import { Point, Polygon, LineString } from "ol/geom";
// import { OSM } from "ol/source";
// import * as olProj from "ol/proj";
// import Overlay from "ol/Overlay";
// import { transform, toLonLat, fromLonLat } from "ol/proj";
// import { toStringHDMS } from "ol/coordinate";
// import { Fill, Stroke, Circle, Style, Icon, Text } from "ol/style";
// import moment from "moment";
// import * as UploadService from "@/api/admin/SysUploadService"
export default {
  name: 'MapPath1',
  data() {
    return {
      map: null,
      view: null,
      // 坐标数据
      coordinatesData: [
        [110.320042, 20.035132],
        [110.341533, 20.036168],
        [110.371533, 20.036168],
        [110.391533, 20.036168],
        [110.411533, 20.036168]
      ],
      coordinatesData1: [
        [110.320042, 20.055132],
        [110.341533, 20.056168],
        [110.371533, 20.056168]
      ],
      iconImg: {
        // red: require("../../../assets/daping/jzyzt/red.png"),
        // orange: require("../../../assets/daping/jzyzt/orange.png"),
        // blue: require("../../../assets/daping/jzyzt/blue.png"),
        // yellow: require("../../../assets/daping/jzyzt/yellow.png"),
        // start: require("../../../assets/daping/jzyzt/icon1.png"),
        // middle: require("../../../assets/daping/jzyzt/icon2.png"),
        // end: require("../../../assets/daping/jzyzt/icon3.png")
      },
      overlay: null,
      lineVector: null,
      piontVector: null,
      piontArr: [],
      siteArr: [],
      siteNumberArr: [],
      trackTimeArr: [],
      nameArr: [],
      phoneArr: [],
      orderArr: [],
      lineColor: [
        [255, 62, 125, 1],
        [69, 130, 255, 1],
        [0, 191, 92, 1],
        [255, 110, 27, 1],
        [213, 65, 226, 1]
      ],
      isPopupShow: false,
      infoArr: [],
      pathPrefix: UploadService.uploadApi.filePathPrefix // 图片路径服务器地址
    }
  },
  mounted() {
    // this.view = new View({
    //   projection: "EPSG:4326",
    //   center: [110.320042, 20.035132],
    //   zoom: 12,
    //   minZoom: 6
    // });
    // this.map = new Map({
    //   target: "map",
    //   view: this.view
    // });
    // this.map.addLayer(
    //   new LayerGroup({
    //     layers: this.layerData()
    //   })
    // );
    // // 弹框
    // this.addPopup();
  },
  methods: {
    onSelect(phone) {
      // debugger;
      let _this = this
      let num = 0
      let len = this.phoneArr.length
      this.phoneArr.forEach((item, index) => {
        // 利用电话号码的唯一性，找出选中人员的轨迹点
        if (item == phone) {
          if (_this.piontArr[index].length > 0) {
            // console.log(index, _this.piontArr[index][0]);
            _this.view.animate({
              center: _this.piontArr[index][0], // 地图移动到选中人员的第一个经纬点
              duration: 1000
            })
          }
        } else {
          num++
        }
      })
      if (num == len) {
        this.$message.warning('无轨迹点信息')
      }
    },
    addPopup() {
      // 使用变量存储弹窗所需的 DOM 对象
      var container = document.getElementById('popup')
      var closer = document.getElementById('popup-closer')
      var content = document.getElementById('popup-content')

      // 创建一个弹窗 Overlay 对象
      this.overlay = new Overlay({
        element: container, // 绑定 Overlay 对象和 DOM 对象的
        autoPan: true, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
        autoPanAnimation: {
          duration: 250 // 自动平移效果的动画时间 9毫秒
        }
      })
      // 将弹窗添加到 map 地图中
      this.map.addOverlay(this.overlay)
      let _that = this
      this.map.on('click', function(evt) {
        var feature = _that.map.forEachFeatureAtPixel(evt.pixel, function(
          feature
        ) {
          return feature
        })
        if (feature) {
          _that.isPopupShow = true
          //   if (feature.getProperties().features) {
          // 聚合情况下
          let infoIndexArr = feature
            .getProperties()
            .attribute.infoIndex.split(',')
            .map(Number) // 字符数组转换为数字数组

          //   debugger;
          //   }
          let coordinate = transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326')
          // 点击尺 （这里是尺(米)，并不是经纬度）;
          //   let hdms = toStringHDMS(toLonLat(evt.coordinate)); // 转换为经纬度显示

          //   content.innerHTML = `
          //             <p>你点击了这里：</p>
          //             <p>经纬度：<p><code> ${hdms}  </code> <p>
          //             <p>坐标：</p>X：${coordinate[0]} &nbsp;&nbsp; Y: ${coordinate[1]}`;
          //   console.log(_that.siteNumberArr);
          //   debugger;
          content.innerHTML =
            `
		    <div class="title">
				<p>` +
            _that.nameArr[infoIndexArr[0]] +
            `（轨迹点` +
            _that.orderArr[infoIndexArr[0]][infoIndexArr[1]] +
            `）</p>
          <img src="` +
            _that.getIcon(_that.phoneArr[infoIndexArr[0]]) +
            `" alt="" />
			</div>
			<div class="content">
				<p>当前定位点数目：<span>` +
            _that.siteNumberArr[infoIndexArr[0]][infoIndexArr[1]] +
            `</span></p>
        <p>定位时间：<span>` +
            // _that.trackTimeArr[infoIndexArr[0]][infoIndexArr[1]]+
            moment(
              parseFloat(
                _that.trackTimeArr[infoIndexArr[0]][infoIndexArr[1]] * 1000
              )
            ).format('YYYY-MM-DD HH:mm:ss') +
            `</span></p>
				<p>定位地点：<span>` +
            _that.siteArr[infoIndexArr[0]][infoIndexArr[1]] +
            `</span></p>
			</div>`
          _that.overlay.setPosition(evt.coordinate) // 把 overlay 显示到指定的 x,y坐标
        } else {
          _that.overlay.setPosition(undefined)
          closer.blur()
        }
      })

      /**
       * 为弹窗添加一个响应关闭的函数
       */
    },
    // 添加图层（金拓维电子地图）
    layerData() {
      let data = []
      data.push(
        new TileLayer({
          source: new TileWMS(this.$globalConfig.mapConfig.PROPL_ZW) // （省级行政区划）
        })
      )
      data.push(
        new TileLayer({
          source: new TileWMS(this.$globalConfig.mapConfig.VEGPL_ZW) // （植被面）
        })
      )
      data.push(
        new TileLayer({
          source: new TileWMS(this.$globalConfig.mapConfig.HYDPL_ZW) // （水系面）
        })
      )
      data.push(
        new TileLayer({
          source: new TileWMS(this.$globalConfig.mapConfig.RESPL_ZW) // （居民地面）
        })
      )
      data.push(
        new TileLayer({
          source: new TileWMS(this.$globalConfig.mapConfig.RAILN_ZW) // （铁路线）
        })
      )
      data.push(
        new TileLayer({
          source: new TileWMS(this.$globalConfig.mapConfig.ROALN_ZW) // （道路线）
        })
      )
      data.push(
        new TileLayer({
          source: new TileWMS(this.$globalConfig.mapConfig.PLAPT_ZW) // （地名地址）
        })
      )
      return data
    },
    // 根据经纬点绘制轨迹点
    drawPoint() {
      let vectorSource = new VectorSource()
      //   console.log(this.piontArr);
      this.piontArr.forEach((item1, index1) => {
        let len = item1.length - 1
        item1.forEach((item2, index2) => {
          let attr = {
            // userName: userName[i],
            // lat: lat[i],
            // lon: lon[i],
            // address: monthYear[i],
            // code: code[i],
            // phone: waterUse[i]
            // siteNumber: this.siteNumberArr[index1][index2]
            infoIndex: index1 + ',' + index2 // 循环轨迹点，记录其在二维数组的索引位置
          }
          let feature = new Feature({
            geometry: new Point(item2),
            // 添加标记信息，点击弹框时候使用
            attribute: attr
          })
          // 匹配轨迹点图片和文字
          let url = ''
          let piontText = ''
          if (index2 == 0) {
            url = this.iconImg.start
            piontText = ''
          } else if (index2 == len) {
            url = this.iconImg.end
            piontText = ''
          } else {
            url = this.iconImg.middle
            piontText = this.orderArr[index1][index2]
            // console.log(this.orderArr[index1][index2])
            // piontText = this.orderArr[index1][index2]+"||"+this.piontArr[index1][index2];
          }
          // 根据不同参数去设置点样式
          var styles = new Style({
            image: new Icon({
              src: url,
              opacity: 1
            }),
            text: new Text({
              textAlign: 'center',
              textBaseline: 'middle',
              font: ' 20px serif',
              text: '' + piontText, // 这里是要写的内容分
              fill: new Fill({
                color: '#eee'
              }),
              stroke: new Stroke({ color: 'rgba(255,255,255,1)' }),
              offsetX: 0,
              offsetY: 0, // 调整相对位置
              rotation: 0
            })
          })
          feature.setStyle(styles)
          vectorSource.addFeature(feature)
        })
      })
      this.piontVector = new vectorLayer({ source: vectorSource })
      this.map.addLayer(this.piontVector)
    },
    // 根据经纬点绘制线
    toline() {
      let vectorSource = new VectorSource()
      this.piontArr.forEach((item, index) => {
        var feature = new Feature({
          geometry: new LineString(item)
        })
        feature.setStyle(
          new Style({
            stroke: new Stroke({
              width: 2,
              color: this.lineColor[index]
            })
          })
        )
        vectorSource.addFeature(feature)
      })
      this.lineVector = new vectorLayer({ source: vectorSource })
      this.map.addLayer(this.lineVector)
    },
    onCheck(data, arr) {
      this.infoArr = arr
      this.onReset()
      // 数据转换
      this.changeData(data)
      // 画线
      this.toline()
      // 画轨迹点
      this.drawPoint()
      // 地图移动到第一个轨迹点
      if (this.piontArr[0].length > 0) {
        this.view.animate({
          center: this.piontArr[0][0],
          duration: 1000
        })
      }
    },
    changeData(data) {
      // debugger
      data.forEach((item1, index1) => {
        let piontArr = []
        let siteArr = []
        let siteNumberArr = []
        let trackTimeArr = []
        let phoneArr = []
        let orderArr = []
        // debugger
        if (item1.trackInfoList.length > 0) {
          this.nameArr.push(item1.name)
          this.phoneArr.push(item1.phone)
          item1.trackInfoList.forEach((item2, index2) => {
            // 画点，线需要转换为数字数组
            piontArr.push([
              parseFloat(item2.latitude),
              parseFloat(item2.longitude)
            ])
            siteArr.push(item2.site)
            siteNumberArr.push(item2.siteNumber)
            trackTimeArr.push(item2.trackTime)
            orderArr.push(index2 + 1)
          })
          // 大数据给的轨迹点是按时间从大到小排列的，所有要把轨迹点数据倒序
          piontArr.reverse()
          siteArr.reverse()
          siteNumberArr.reverse()
          trackTimeArr.reverse()
          // console.log(this.trackTimeArr);
          this.piontArr.push(piontArr)
          this.siteArr.push(siteArr)
          this.siteNumberArr.push(siteNumberArr)
          this.trackTimeArr.push(trackTimeArr)
          this.orderArr.push(orderArr)
          // console.log(this.orderArr);
          // console.log(this.piontArr);
        } else {
          // debugger
          this.$message.warning(item1.name + ' 无轨迹点信息')
        }
      })
      // debugger;
    },
    onReset() {
      this.piontArr = []
      this.siteArr = []
      this.siteNumberArr = []
      this.trackTimeArr = []
      this.nameArr = []
      this.phoneArr = []
      this.orderArr = []
      this.map.removeLayer(this.piontVector)
      this.map.removeLayer(this.lineVector)
    },
    getIcon(phone) {
      let iconName = ''
      this.infoArr.forEach(item => {
        if (item.phone == phone) {
          iconName = item.iconName
        }
      })
      return this.pathPrefix + iconName
    }
  }
}
</script>

<style scoped lang="less">
#map {
  height: 100%;
  width: 100%;
  background-color: #fff;
}

/*隐藏ol的一些自带元素*/
/deep/.ol-attribution,
/deep/.ol-zoom {
  display: none;
}
/deep/.popup-content {
  background-color: #485666;
  border-radius: 5px;
  padding: 10px;
  width: 35vh;
  .title {
    position: relative;
    p {
      background-color: #f4cd28;
      padding: 5px 10px;
      font-size: 1.8vh;
      font-weight: bold;
      max-width: 23vh;
      color: #000;
    }
    img {
      width: 8vh;
      height: 8vh;
      border-radius: 90%;
      position: absolute;
      right: 0;
      top: -3.2vh;
    }
  }
  .content {
    // margin-top: 10px;
    background-color: #373737;
    padding: 10px;
    p {
      color: #fff;
      font-size: 1.5vh;
      padding: 0 0 0 2vh;
      position: relative;
      margin-bottom: 1vh;
    }
    p::before {
      content: "";
      position: absolute;
      left: -0.1vh;
      top: 0.7vh;
      width: 1vh;
      height: 1vh;
      border-radius: 50%;
      background: #f4cd28;
    }
  }
}
</style>
